<template>
  <el-card class="attr">
    <el-form inline :disabled="disabled">
      <el-form-item label="一级分类">
        <el-select
          placeholder="请选择一级分类"
          v-model="CategoryStore.category1Id"
        >
          <el-option
            v-for="c1 in CategoryStore.category1List"
            :key="c1.id"
            :label="c1.name"
            :value="c1.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="二级分类">
        <el-select
          placeholder="请选择二级分类"
          v-model="CategoryStore.category2Id"
        >
          <el-option
            v-for="c2 in CategoryStore.category2List"
            :key="c2.id"
            :label="c2.name"
            :value="c2.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="三级分类">
        <el-select
          placeholder="请选择三级分类"
          v-model="CategoryStore.category3Id"
        >
          <el-option
            :label="c3.name"
            :value="c3.id"
            v-for="c3 in CategoryStore.category3List"
            :key="c3.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "CategorySelector",
};
</script>

<script lang="ts" setup>
import { onMounted, ref, watch, onBeforeUnmount } from "vue";
import { useCategoryStore } from "@/stores/category";
import {
  getCategory1ListApi,
  getCategory3ListApi,
  getCategory2ListApi,
} from "@/api/product/category";
import type { CategoryList } from "@/api/product/model/categoryModel";

// const category1List = ref<CategoryList>([]);
// const category2List = ref<CategoryList>([]);
// const category3List = ref<CategoryList>([]);
// const category1Id = ref();
// const category2Id = ref();
// const category3Id = ref();
defineProps<{
  disabled: boolean;
}>();
const CategoryStore = useCategoryStore();
onMounted(() => {
  CategoryStore.getCategory1List();
});

watch(
  () => CategoryStore.category1Id,
  (newVal) => {
    CategoryStore.getCategory2List(newVal as number);
  }
);
watch(
  () => CategoryStore.category2Id,
  (newVal) => {
    if (!newVal) return;
    CategoryStore.getCategory3List(newVal as number);
  }
);
onBeforeUnmount(() => {
  CategoryStore.category1Id = undefined;
  CategoryStore.category2Id = undefined;
  CategoryStore.category3Id = undefined;
  CategoryStore.category1List = [];
  CategoryStore.category2List = [];
  CategoryStore.category3List = [];
});
</script>

<style scoped>
.attr :deep(.el-form-item) {
  margin-top: 10px;
  margin-bottom: 10px;
}
</style>
